const Mock = require('mockjs')
const bodyParser = require('body-parser')
const jwt = require('jsonwebtoken')
var data = Mock.mock({
  'cart|50': [
    {
      'id|+1': 1,
      img: '@image(100x200, @color(), @ctitle())',
      count: 1,
      price: '@integer(1, 100)',
      goodsName: '@ctitle(5)',
    },
  ],
})

const userInfo = [
  {
    username: 'admin',
    password: '123',
  },
  {
    username: 'super-admin',
    password: '321',
  },
]

module.exports = (app) => {
  // 解析post传递的body参数
  app.use(bodyParser.json())

  app.post('/api/login', (req, res) => {
    const { username, password } = req.body
    const status = userInfo.some((v) => v.username === username && v.password === password)
    if (status) {
      const token = jwt.sign({ username }, 'secret_key', { expiresIn: '24h' })
      res.json({
        code: 1,
        msg: 'success',
        data: {
          token,
        },
      })
    } else {
      res.json({
        code: -1,
        msg: '登陆失败，请重试',
      })
    }
  })

  app.get('/api/list', (req, res) => {
    const { page = 1, size = 5 } = req.query
    res.json({
      code: 0,
      msg: 'success',
      data: {
        total: data.cart.length,
        list: data.cart.slice((page - 1) * size, page * size),
      },
    })
  })
}
